package com.quark.controller.system;

import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quark.model.system.gen.GenConfig;
import com.quark.result.RequestResult;
import com.quark.service.system.GenTableColumnService;
import com.quark.service.system.GeneratorService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * @author 张高昌
 * @date 2022/1/26 18:25
 * @description: 代码生成
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/generator")
public class GeneratorController {

    private final GeneratorService generatorService;

    private final GenTableColumnService genTableColumnService;

    /**
     * 表的列表
     *
     * @param page
     * @param tableName 参数集
     * @param dsName    数据源编号
     * @return
     * @author 张高昌
     * @date 2022/1/26 18:29
     */
    @GetMapping("/page")
    public RequestResult getPage(Page page, String tableName, String dsName) {

        return RequestResult.success(generatorService.getPage(page, tableName, dsName));
    }

    /**
     * 字段预览
     *
     * @param page
     * @param genConfig
     * @return
     * @author 张高昌
     * @date 2022/1/26 18:29
     */
    @GetMapping("/table")
    public RequestResult getTable(Page page, GenConfig genConfig) {
        return RequestResult.success(genTableColumnService.listTable(page, genConfig));
    }

    /**
     * 预览
     *
     * @param genConfig
     * @return
     * @author 张高昌
     * @date 2022/1/29 14:53
     */
    @GetMapping("/preview")
    public RequestResult previewCode(GenConfig genConfig) {
        return RequestResult.success(generatorService.previewCode(genConfig));
    }

    /**
     * 生成代码
     *
     * @param genConfig
     * @param response
     * @author 张高昌
     * @date 2022/2/02 19:41 大年初二
     */
    @SneakyThrows
    @PostMapping("/code")
    public void generatorCode(@RequestBody GenConfig genConfig, HttpServletResponse response) {

        byte[] data = generatorService.generatorCode(genConfig);
        response.reset();
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                String.format("attachment; filename=%s.zip" , genConfig.getTableName()));
        response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
        response.setContentType("application/octet-stream; charset=UTF-8");
        response.setHeader("requestType","file");  // 自定义的header
        response.setHeader("Access-Control-Expose-Headers", "requestType"); //设置这个header 可见

        IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
    }

}
